// 导入需要使用的模块
const express = require("express");
const pool = require("../pool");

// token生成
const jwt = require("../jwt");
// 加载MD5模块
const md5 = require("md5");
// 用于短信验证码模块
const { randomCode, sendCode } = require("../utils/getMessage");
// 路由名，需要用到自己换
const router = express.Router();

// 验证码接口
router.post("/loginphone/code", (req, res) => {
  let { uphone } = req.body;
  let sql = "update user_information set phonecode=? where wphone=?;";
  let sql1 = "update user_information set phonecode=null where wphone=?;";
  let code = randomCode(6); //生成6位数字随机验证码
  // let code = 001122
  sendCode(`${uphone}`, code, function (success) {
    if (success) {
      setTimeout(() => {
        console.log(1);
        pool.query(sql1, [uphone], (error, results) => {
          if (error) throw error;
          console.log(`删除${results}`);
        });
      }, 60000);

      pool.query(sql, [code, uphone], (error, results) => {
        if (error) throw error;
        console.log(results);
        if (results.affectedRows === 0) {
          res.send({
            message: "短信验证码发送成功",
            status: 201,
            code: code,
            data: {
              res: "该手机号没有注册",
            },
          });
        } else {
          res.send({
            message: "短信验证码发送成功",
            status: 200,
            code: code,
            data: {
              res: "该手机已经注册",
            },
          });
        }
      });
    } else {
      res.send({ message: "短信验证码发送失败", status: 303 });
    }
  });
});

// 登录请求
router.post("/loginphone", (req, res) => {
  let { uphone, upsd } = req.body;
  // SQL语句
  // let sql = 'SELECT id,username,nickname,avatar FROM xzqa_author WHERE (email=? || phone=?) AND password=MD5(?)';
  let sql =
    "select * from user_information where wphone=? and phonecode=?";
  pool.query(sql, [uphone, upsd], (error, results) => {
    if (error) throw error;
    if (results.length == 0) {
      //登录失败
      res.send({ message: "登录失败", status: 201 });
    } else {
      console.log(results); //登录成功
      res.send({
        message: "登录成功",
        status: 200,
        result: results[0],
        token: jwt.generateToken(results[0]),
      });
    }
  });
});

// router.beforeEach((to, from, next) => {
//   // to and from are both route objects. must call `next`.
// })
// 记得导出
module.exports = router;
